package com.wang.interview.tests.threadtest;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: wang
 * @date: 2021/8/17 16:54
 * @description: threadLocal 通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象，其他线程是不需要访问的，也访问不到的。各个线程中访问的是不同的对象。
 */
public class T5 {
    public static void main(String[] args) {
        Stu xiaowei = new Stu("xiaowei", 22);
        ThreadLocal<Stu> threadLocal = new ThreadLocal<>();
        threadLocal.set(xiaowei);

        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 5, 10, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
        for (int i = 0; i < 10; i++) {
            if ( i ==  5 ){
                Stu stu = threadLocal.get();
                //System.out.println("stu是不是同一个："+(stu == xiaowei));  // stu是不是同一个：true
                stu.setName("xaiozhi");
                threadLocal.set(stu);
                //System.out.println(threadLocal.get().getName());   // xaiozhi, 说明可以在没有
            }
            pool.submit(()->{
                System.out.println(1);
                // 没有结果因为这个线程get的是自己线程的ThreadLocals的属性，而现在根本就没有set
                System.out.println(Thread.currentThread().getName()+"\t "+threadLocal.get().getName());
                System.out.println(2);
            });
        }
        pool.shutdown();
    }
}
class Stu{
    private String name;
    private int age;

    public Stu() {
    }

    public Stu(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Stu{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
